//
//  HDSSFWAPIService.swift
//  Excited
//
//  Created by X140Yu on 7/31/16.
//  Copyright © 2016 X140Yu. All rights reserved.
//

import Foundation
import Moya
import RxSwift


let HDSSFWAPIProvider = RxMoyaProvider<HDSSFWAPIService>(endpointClosure: endpointClosure, requestClosure: requestClosure)

public enum HDSSFWAPIService {
    /// 师生服务的检查
    case SecurityCheck
    /// 获取成绩
    case GetScore
    /// 获取培养方案 ID
    case GetPYFAID
    /// 获取培养方案
    case GetPYFA
}

extension HDSSFWAPIService: TargetType {
    public var baseURL: NSURL { return NSURL(string: "http://ssfw3.hlju.edu.cn/ssfw")! }
    public var path: String {
        switch self {
        case .SecurityCheck:
            return "/j_spring_ids_security_check"
        case .GetScore:
            return "/zhcx/cjxx.do"
        case .GetPYFAID:
            return "/zhcx/pyfa/xsfaTree.do"
        case .GetPYFA:
            return "/zhcx/pyfa/node.do"
        }
    }
    public var method: Moya.Method {
        switch self {
        case .GetPYFA:
            return .POST
        default:
            return .GET
        }
    }
    public var parameters: [String: AnyObject]? {
        switch self {
        case .GetPYFA:
            break
        default:
            break
        }
        return nil
    }
    public var sampleData: NSData {
        return "fuck".dataUsingEncoding(NSUTF8StringEncoding)!
    }
    public var multipartBody: [MultipartFormData]? {
        return nil
    }
}

private let endpointClosure: MoyaProvider<HDSSFWAPIService>.EndpointClosure = { (target) -> Endpoint<HDSSFWAPIService> in
    let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
    var endpoint: Endpoint<HDSSFWAPIService> = Endpoint<HDSSFWAPIService>(URL: url, sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)

    debugPrint("-- Request --")
    debugPrint(url)
    debugPrint(target.method)
    if let param = target.parameters {
        debugPrint(param)
    }
    debugPrint("-- End --")

    if target == .SecurityCheck {
        if let cookie = HDCookieManager.sharedInstance.getCookie(.D) {
            return endpoint.endpointByAddingHTTPHeaderFields(["Cookie": cookie])
        }
    } else {
        if let cookie = HDCookieManager.sharedInstance.getCookie(.E) {
            return endpoint.endpointByAddingHTTPHeaderFields(["Cookie": cookie])
        }
    }
    return endpoint
}

private let requestClosure: MoyaProvider<HDSSFWAPIService>.RequestClosure = { (endpoint, done) in
    let request: NSMutableURLRequest = endpoint.urlRequest.mutableCopy() as! NSMutableURLRequest
    if endpoint.method == .POST {
        if let pyfaID = HDCache.sharedInstance.getPYFAID() {
            let param = "param=%7B%22pyfadm%22%3A%22\(pyfaID)%22%2C%22nodeType%22%3A%22-99%22%2C%22nodeValue%22%3A%22root%22%2C%22sfggkz%22%3A%220%22%7D%0A"
            let myNSData = (param as String).dataUsingEncoding(NSUTF8StringEncoding)!
            request.HTTPBody = myNSData
        }
    }
    request.HTTPShouldHandleCookies = false
    request.timeoutInterval = 10
    debugPrint(request.allHTTPHeaderFields)
    let cookieJar = NSHTTPCookieStorage.sharedHTTPCookieStorage()
    for cook in cookieJar.cookies! {
        cookieJar.deleteCookie(cook)
    }
    done(.Success(request))
}